package com.itheima.spring.service.impl;

import com.itheima.spring.dao.AccountDao;
import com.itheima.spring.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

@Service //装配到spring容器中
public class AccountServiceImpl implements AccountService {

    //自动注入
    @Autowired
    private AccountDao accountDao;

    //注入dataSource数据源
    @Autowired
    private DataSource dataSource;

    @Override
    public void transfer(String inName, String outName, int money) {
        Connection connection=null;

        try {
            //获取连接对象
            connection = dataSource.getConnection();
            //修改是否自动提交
            connection.setAutoCommit(false);

            //调用转出方法(这里将connection传入进去,让转入转出都使用同一个连接对象)
            accountDao.outUser(connection,outName,money);

            //模拟服务器崩溃异常
            int i=1/0;

            //调用转入方法(这里将connection传入进去,让转入转出都使用同一个连接对象)
            accountDao.inUser(connection,inName,money);

            //提交事务
            connection.commit();
        } catch (Exception e) {
            e.printStackTrace();
            //如果有异常就回滚事务
            try {
                connection.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }finally {
            try {
                //设置为自动提交
                connection.setAutoCommit(true);
                //释放资源
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }


    }
}
